package hanlder

import (
	"context"
	"goods_srv/global"
	"goods_srv/goods"
	"goods_srv/model"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
)

type GoodsService struct {
	goods.UnimplementedGoodsServer
}

// 获取商品详情
func (g *GoodsService) GetGoodsDetail(ctx context.Context, in *goods.GetGoodsDetailRequest) (*goods.GoodsInfo, error) {
	var goodsInfo model.Goods

	tx := global.DB.Model(&model.Goods{}).Where(model.Goods{
		Model: gorm.Model{
			ID: uint(in.GoodsId),
		},
	}).Limit(1).Find(&goodsInfo)

	if tx.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "获取商品详情失败")
	}

	return &goods.GoodsInfo{
		GoodsId: int32(goodsInfo.ID),
		Name:    goodsInfo.Name,
		Desc:    goodsInfo.Desc,
		Price:   float32(goodsInfo.Price),
		Num:     int32(goodsInfo.Num),
		Img:     goodsInfo.Img,
	}, nil
}

// 查询商品列表
func (g *GoodsService) GetGoods(ctx context.Context, in *goods.GoodsListRequest) (*goods.GoodsList, error) {
	var goodsList []*model.Goods

	tx := global.DB.Model(&model.Goods{}).Where("name like ?", "%"+in.Name+"%").Order("num desc").Find(&goodsList)

	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "获取商品列表失败")
	}
	var count int64
	global.DB.Model(&model.Goods{}).Count(&count)

	var data []*goods.GoodsInfo
	for _, v := range goodsList {
		data = append(data, &goods.GoodsInfo{
			GoodsId: int32(v.ID),
			Name:    v.Name,
			Desc:    v.Desc,
			Price:   float32(v.Price),
			Num:     int32(v.Num),
			Img:     v.Img,
		})
	}

	return &goods.GoodsList{
		Total: int32(count),
		Data:  data,
	}, nil
}
